var express = require('express');
var router = express.Router();
var User=require('../models/Users');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/*登陆 */
router.get('/login',function(req,res,next){
  res.locals.success=req.flash("success");
  res.locals.err=req.flash("err");
  res.render('login',{title:'login'});
});

router.post('/login',function(req,res,next){
  User.get(req.body.name,function (err,user) {
    if(err){
      req.flash("err","数据库查询失败");
      return res.redirect("/login"); 
    };
    if(user){
      if(user.password!=req.body.password){
        req.flash("err","密码错误，请重新登陆");
        return res.redirect("/login");
      }else{
      return res.redirect("/");//成功登陆
      };
    };
    req.flash("err","用户名不存在");
    return res.redirect("/login");
  });
 
});

/*注册 */

router.get('/reg',function(req,res,next){
  res.locals.err=req.flash("err");
  res.render('reg',{title:'reg'});
  //视图助手
});

router.post('/reg',function(req,res,next){
 //实例化
  var newUser=new User({
    name:req.body.name,
    password:req.body.password
  });
  //用户名是否重复,否则插入
  User.get(newUser.name,function(err,user){
    if(err){
      req.flash("err","数据库查询失败");
      return res.redirect("/reg"); 
      
    };
    if(user){
      req.flash("err","用户名已存在");
      return res.redirect("/reg"); 
    };
    //插入数据
    newUser.save(function(err){
      if(err){
          req.flash("err","数据库错误，注册失败")
          res.redirect('/reg');
          return;
      };
      req.session.users=user;
      req.flash("success","注册成功,请登陆");
      res.redirect('/login');
      
    });
      
  });
});

 //个人主页
 router.get('/homepage', function(req, res, next) {
  res.render('homepage', { title: 'Home' });
});



module.exports = router;
